home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / url.py < prev    next >
Text File  |  2008-01-17  |  21KB  |  631 lines

  1. # -*- test-case-name: nevow.test.test_url -*-
  2. # Copyright (c) 2004-2007 Divmod.
  3. # See LICENSE for details.
  4.  
  5. """
  6. URL parsing, construction and rendering.
  7. """
  8.  
  9. import weakref
  10. import urlparse
  11. import urllib
  12.  
  13. from zope.interface import implements
  14.  
  15. from twisted.web.util import redirectTo
  16.  
  17. from nevow import inevow, flat
  18. from nevow.stan import raw
  19. from nevow.flat import serialize
  20. from nevow.context import WovenContext
  21.  
  22. def _uqf(query):
  23.     for x in query.split('&'):
  24.         if '=' in x:
  25.             yield tuple( [urllib.unquote_plus(s) for s in x.split('=', 1)] )
  26.         elif x:
  27.             yield (urllib.unquote_plus(x), None)
  28. unquerify = lambda query: list(_uqf(query))
  29.  
  30.  
  31. class URL(object):
  32.     """Represents a URL and provides a convenient API for modifying its parts.
  33.  
  34.     A URL is split into a number of distinct parts: scheme, netloc (domain
  35.     name), path segments, query parameters and fragment identifier.
  36.  
  37.     Methods are provided to modify many of the parts of the URL, especially
  38.     the path and query parameters. Values can be passed to methods as-is;
  39.     encoding and escaping is handled automatically.
  40.  
  41.     There are a number of ways to create a URL:
  42.         * Standard Python creation, i.e. __init__.
  43.         * fromString, a class method that parses a string.
  44.         * fromContext, a class method that creates a URL to represent the
  45.           current URL in the path traversal process.
  46.  
  47.     URL instances can be used in a stan tree or to fill template slots. They can
  48.     also be used as a redirect mechanism - simply return an instance from an
  49.     IResource method. See URLRedirectAdapter for details.
  50.  
  51.     URL subclasses with different constructor signatures should override
  52.     L{cloneURL} to ensure that the numerous instance methods which return
  53.     copies do so correctly.  Additionally, the L{fromString}, L{fromContext}
  54.     and L{fromRequest} class methods need overriding.
  55.  
  56.     @type fragment: C{str}
  57.     @ivar fragment: The fragment portion of the URL.
  58.     """
  59.  
  60.     def __init__(self, scheme='http', netloc='localhost', pathsegs=None,
  61.                  querysegs=None, fragment=None):
  62.         self.scheme = scheme
  63.         self.netloc = netloc
  64.         if pathsegs is None:
  65.             pathsegs = ['']
  66.         self._qpathlist = pathsegs
  67.         if querysegs is None:
  68.             querysegs = []
  69.         self._querylist = querysegs
  70.         if fragment is None:
  71.             fragment = ''
  72.         self.fragment = fragment
  73.  
  74.  
  75.     def path():
  76.         def get(self):
  77.             return '/'.join([
  78.                     # Note that this set of safe things is pretty arbitrary.
  79.                     # It is this particular set in order to match that used by
  80.                     # nevow.flat.flatstan.StringSerializer, so that url.path
  81.                     # will give something which is contained by flatten(url).
  82.                     urllib.quote(seg, safe="-_.!*'()") for seg in self._qpathlist])
  83.         doc = """
  84.         The path portion of the URL.
  85.         """
  86.         return get, None, None, doc
  87.     path = property(*path())
  88.  
  89.     def __eq__(self, other):
  90.         if not isinstance(other, self.__class__):
  91.             return NotImplemented
  92.         for attr in ['scheme', 'netloc', '_qpathlist', '_querylist', 'fragment']:
  93.             if getattr(self, attr) != getattr(other, attr):
  94.                 return False
  95.         return True
  96.  
  97.     def __ne__(self, other):
  98.         if not isinstance(other, self.__class__):
  99.             return NotImplemented
  100.         return not self.__eq__(other)
  101.  
  102.     query = property(
  103.         lambda self: [y is None and x or '='.join((x,y))
  104.             for (x,y) in self._querylist]
  105.         )
  106.  
  107.     def _pathMod(self, newpathsegs, newqueryparts):
  108.         return self.cloneURL(self.scheme,
  109.                              self.netloc,
  110.                              newpathsegs,
  111.                              newqueryparts,
  112.                              self.fragment)
  113.  
  114.  
  115.     def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment):
  116.         """
  117.         Make a new instance of C{self.__class__}, passing along the given
  118.         arguments to its constructor.
  119.         """
  120.         return self.__class__(scheme, netloc, pathsegs, querysegs, fragment)
  121.  
  122.  
  123.     ## class methods used to build URL objects ##
  124.  
  125.     def fromString(klass, st):
  126.         scheme, netloc, path, query, fragment = urlparse.urlsplit(st)
  127.         u = klass(
  128.             scheme, netloc,
  129.             [urllib.unquote(seg) for seg in path.split('/')[1:]],
  130.             unquerify(query), fragment)
  131.         return u
  132.     fromString = classmethod(fromString)
  133.  
  134.     def fromRequest(klass, request):
  135.         """
  136.         Create a new L{URL} instance which is the same as the URL represented
  137.         by C{request} except that it includes only the path segments which have
  138.         already been processed.
  139.         """
  140.         uri = request.prePathURL()
  141.         if '?' in request.uri:
  142.             uri += '?' + request.uri.split('?')[-1]
  143.         return klass.fromString(uri)
  144.     fromRequest = classmethod(fromRequest)
  145.  
  146.     def fromContext(klass, context):
  147.         '''Create a URL object that represents the current URL in the traversal
  148.         process.'''
  149.         request = inevow.IRequest(context)
  150.         uri = request.prePathURL()
  151.         if '?' in request.uri:
  152.             uri += '?' + request.uri.split('?')[-1]
  153.         return klass.fromString(uri)
  154.     fromContext = classmethod(fromContext)
  155.  
  156.     ## path manipulations ##
  157.  
  158.     def pathList(self, unquote=False, copy=True):
  159.         result = self._qpathlist
  160.         if unquote:
  161.             result = map(urllib.unquote, result)
  162.         if copy:
  163.             result = result[:]
  164.         return result
  165.  
  166.     def sibling(self, path):
  167.         """Construct a url where the given path segment is a sibling of this url
  168.         """
  169.         l = self.pathList()
  170.         l[-1] = path
  171.         return self._pathMod(l, self.queryList(0))
  172.  
  173.     def child(self, path):
  174.         """Construct a url where the given path segment is a child of this url
  175.         """
  176.         l = self.pathList()
  177.         if l[-1] == '':
  178.             l[-1] = path
  179.         else:
  180.             l.append(path)
  181.         return self._pathMod(l, self.queryList(0))
  182.  
  183.     def isRoot(self, pathlist):
  184.         return (pathlist == [''] or not pathlist)
  185.  
  186.     def parent(self):
  187.         import warnings
  188.         warnings.warn(
  189.             "[v0.4] URL.parent has been deprecated and replaced with parentdir (which does what parent used to do) and up (which does what you probably thought parent would do ;-))",
  190.             DeprecationWarning,
  191.             stacklevel=2)
  192.         return self.parentdir()
  193.  
  194.     def curdir(self):
  195.         """Construct a url which is a logical equivalent to '.'
  196.         of the current url. For example:
  197.  
  198.         >>> print URL.fromString('http://foo.com/bar').curdir()
  199.         http://foo.com/
  200.         >>> print URL.fromString('http://foo.com/bar/').curdir()
  201.         http://foo.com/bar/
  202.         """
  203.         l = self.pathList()
  204.         if l[-1] != '':
  205.             l[-1] = ''
  206.         return self._pathMod(l, self.queryList(0))
  207.  
  208.     def up(self):
  209.         """Pop a URL segment from this url.
  210.         """
  211.         l = self.pathList()
  212.         if len(l):
  213.             l.pop()
  214.         return self._pathMod(l, self.queryList(0))
  215.  
  216.     def parentdir(self):
  217.         """Construct a url which is the parent of this url's directory;
  218.         This is logically equivalent to '..' of the current url.
  219.         For example:
  220.  
  221.         >>> print URL.fromString('http://foo.com/bar/file').parentdir()
  222.         http://foo.com/
  223.         >>> print URL.fromString('http://foo.com/bar/dir/').parentdir()
  224.         http://foo.com/bar/
  225.         """
  226.         l = self.pathList()
  227.         if not self.isRoot(l) and l[-1] == '':
  228.             del l[-2]
  229.         else:
  230.             # we are a file, such as http://example.com/foo/bar our
  231.             # parent directory is http://example.com/
  232.             l.pop()
  233.             if self.isRoot(l): l.append('')
  234.             else: l[-1] = ''
  235.         return self._pathMod(l, self.queryList(0))
  236.  
  237.     def click(self, href):
  238.         """Build a path by merging 'href' and this path.
  239.  
  240.         Return a path which is the URL where a browser would presumably
  241.         take you if you clicked on a link with an 'href' as given.
  242.         """
  243.         scheme, netloc, path, query, fragment = urlparse.urlsplit(href)
  244.  
  245.         if (scheme, netloc, path, query, fragment) == ('', '', '', '', ''):
  246.             return self
  247.  
  248.         query = unquerify(query)
  249.  
  250.         if scheme:
  251.             if path and path[0] == '/':
  252.                 path = path[1:]
  253.             return self.cloneURL(
  254.                 scheme, netloc, map(raw, path.split('/')), query, fragment)
  255.         else:
  256.             scheme = self.scheme
  257.  
  258.         if not netloc:
  259.             netloc = self.netloc
  260.             if not path:
  261.                 path = self.path
  262.                 if not query:
  263.                     query = self._querylist
  264.                     if not fragment:
  265.                         fragment = self.fragment
  266.             else:
  267.                 if path[0] == '/':
  268.                     path = path[1:]
  269.                 else:
  270.                     l = self.pathList()
  271.                     l[-1] = path
  272.                     path = '/'.join(l)
  273.  
  274.         path = normURLPath(path)
  275.         return self.cloneURL(
  276.             scheme, netloc, map(raw, path.split('/')), query, fragment)
  277.  
  278.     ## query manipulation ##
  279.  
  280.     def queryList(self, copy=True):
  281.         """Return current query as a list of tuples."""
  282.         if copy:
  283.             return self._querylist[:]
  284.         return self._querylist
  285.  
  286.     # FIXME: here we call str() on query arg values: is this right?
  287.  
  288.     def add(self, name, value=None):
  289.         """Add a query argument with the given value
  290.         None indicates that the argument has no value
  291.         """
  292.         q = self.queryList()
  293.         q.append((name, value))
  294.         return self._pathMod(self.pathList(copy=False), q)
  295.  
  296.     def replace(self, name, value=None):
  297.         """
  298.         Remove all existing occurrences of the query argument 'name', *if it
  299.         exists*, then add the argument with the given value.
  300.  
  301.         C{None} indicates that the argument has no value.
  302.         """
  303.         ql = self.queryList(False)
  304.         ## Preserve the original position of the query key in the list
  305.         i = 0
  306.         for (k, v) in ql:
  307.             if k == name:
  308.                 break
  309.             i += 1
  310.         q = filter(lambda x: x[0] != name, ql)
  311.         q.insert(i, (name, value))
  312.         return self._pathMod(self.pathList(copy=False), q)
  313.  
  314.     def remove(self, name):
  315.         """Remove all query arguments with the given name
  316.         """
  317.         return self._pathMod(
  318.             self.pathList(copy=False),
  319.             filter(
  320.                 lambda x: x[0] != name, self.queryList(False)))
  321.  
  322.     def clear(self, name=None):
  323.         """Remove all existing query arguments
  324.         """
  325.         if name is None:
  326.             q = []
  327.         else:
  328.             q = filter(lambda x: x[0] != name, self.queryList(False))
  329.         return self._pathMod(self.pathList(copy=False), q)
  330.  
  331.     ## scheme manipulation ##
  332.  
  333.     def secure(self, secure=True, port=None):
  334.         """Modify the scheme to https/http and return the new URL.
  335.  
  336.         @param secure: choose between https and http, default to True (https)
  337.         @param port: port, override the scheme's normal port
  338.         """
  339.  
  340.         # Choose the scheme and default port.
  341.         if secure:
  342.             scheme, defaultPort = 'https', 443
  343.         else:
  344.             scheme, defaultPort = 'http', 80
  345.  
  346.         # Rebuild the netloc with port if not default.
  347.         netloc = self.netloc.split(':',1)[0]
  348.         if port is not None and port != defaultPort:
  349.             netloc = '%s:%d' % (netloc, port)
  350.  
  351.         return self.cloneURL(
  352.             scheme, netloc, self._qpathlist, self._querylist, self.fragment)
  353.  
  354.     ## fragment/anchor manipulation
  355.  
  356.     def anchor(self, anchor=None):
  357.         """
  358.         Modify the fragment/anchor and return a new URL. An anchor of
  359.         C{None} (the default) or C{''} (the empty string) will remove the
  360.         current anchor.
  361.         """
  362.         return self.cloneURL(
  363.             self.scheme, self.netloc, self._qpathlist, self._querylist, anchor)
  364.  
  365.     ## object protocol override ##
  366.  
  367.     def __str__(self):
  368.         return str(flat.flatten(self))
  369.  
  370.     def __repr__(self):
  371.         return (
  372.             '%s(scheme=%r, netloc=%r, pathsegs=%r, querysegs=%r, fragment=%r)'
  373.             % (self.__class__,
  374.                self.scheme,
  375.                self.netloc,
  376.                self._qpathlist,
  377.                self._querylist,
  378.                self.fragment))
  379.  
  380.  
  381. def normURLPath(path):
  382.     """
  383.     Normalise the URL path by resolving segments of '.' and '..'.
  384.     """
  385.     segs = []
  386.  
  387.     pathSegs = path.split('/')
  388.  
  389.     for seg in pathSegs:
  390.         if seg == '.':
  391.             pass
  392.         elif seg == '..':
  393.             if segs:
  394.                 segs.pop()
  395.         else:
  396.             segs.append(seg)
  397.  
  398.     if pathSegs[-1:] in (['.'],['..']):
  399.         segs.append('')
  400.  
  401.     return '/'.join(segs)
  402.  
  403.  
  404. class URLOverlay(object):
  405.     def __init__(self, urlaccessor, doc=None, dolater=None, keep=None):
  406.         """A Proto like object for abstractly specifying urls in stan trees.
  407.  
  408.         @param urlaccessor: a function which takes context and returns a URL
  409.  
  410.         @param doc: a a string documenting this URLOverlay instance's usage
  411.  
  412.         @param dolater: a list of tuples of (command, args, kw) where
  413.         command is a string, args is a tuple and kw is a dict; when the
  414.         URL is returned from urlaccessor during rendering, these
  415.         methods will be applied to the URL in order
  416.         """
  417.         if doc is not None:
  418.             self.__doc__ = doc
  419.         self.urlaccessor = urlaccessor
  420.         if dolater is None:
  421.             dolater= []
  422.         self.dolater = dolater
  423.         if keep is None:
  424.             keep = []
  425.         self._keep = keep
  426.  
  427.     def addCommand(self, cmd, args, kw):
  428.         dl = self.dolater[:]
  429.         dl.append((cmd, args, kw))
  430.         return self.__class__(self.urlaccessor, dolater=dl, keep=self._keep[:])
  431.  
  432.     def keep(self, *args):
  433.         """A list of arguments to carry over from the previous url.
  434.         """
  435.         K = self._keep[:]
  436.         K.extend(args)
  437.         return self.__class__(self.urlaccessor, dolater=self.dolater[:], keep=K)
  438.  
  439.  
  440. def createForwarder(cmd):
  441.     return lambda self, *args, **kw: self.addCommand(cmd, args, kw)
  442.  
  443.  
  444. for cmd in [
  445.     'sibling', 'child', 'parent', 'here', 'curdir', 'click', 'add',
  446.     'replace', 'clear', 'remove', 'secure', 'anchor', 'up', 'parentdir'
  447.     ]:
  448.     setattr(URLOverlay, cmd, createForwarder(cmd))
  449.  
  450.  
  451. def hereaccessor(context):
  452.     return URL.fromContext(context).clear()
  453. here = URLOverlay(
  454.     hereaccessor,
  455.     "A lazy url construction object representing the current page's URL. "
  456.     "The URL which will be used will be determined at render time by "
  457.     "looking at the request. Any query parameters will be "
  458.     "cleared automatically.")
  459.  
  460.  
  461. def gethereaccessor(context):
  462.     return URL.fromContext(context)
  463. gethere = URLOverlay(gethereaccessor,
  464.     "A lazy url construction object like 'here' except query parameters "
  465.     "are preserved. Useful for constructing a URL to this same object "
  466.     "when query parameters need to be preserved but modified slightly.")
  467.  
  468.  
  469.  
  470. def viewhereaccessor(context):
  471.     U = hereaccessor(context)
  472.     i = 1
  473.     while True:
  474.         try:
  475.             params = context.locate(inevow.IViewParameters, depth=i)
  476.         except KeyError:
  477.             break
  478.         for (cmd, args, kw) in iter(params):
  479.             U = getattr(U, cmd)(*args, **kw)
  480.         i += 1
  481.     return U
  482. viewhere = URLOverlay(viewhereaccessor,
  483.     "A lazy url construction object like 'here' IViewParameters objects "
  484.     "are looked up in the context during rendering. Commands provided by "
  485.     "any found IViewParameters objects are applied to the URL object before "
  486.     "rendering it.")
  487.  
  488.  
  489. def rootaccessor(context):
  490.     req = context.locate(inevow.IRequest)
  491.     root = req.getRootURL()
  492.     if root is None:
  493.         return URL.fromContext(context).click('/')
  494.     return URL.fromString(root)
  495. root = URLOverlay(rootaccessor,
  496.     "A lazy URL construction object representing the root of the "
  497.     "application. Normally, this will just be the logical '/', but if "
  498.     "request.rememberRootURL() has previously been used in "
  499.     "the request traversal process, the url of the resource "
  500.     "where rememberRootURL was called will be used instead.")
  501.  
  502.  
  503. def URLSerializer(original, context):
  504.     """
  505.     Serialize the given L{URL}.
  506.  
  507.     Unicode path, query and fragment components are handled according to the
  508.     IRI standard (RFC 3987).
  509.     """
  510.     def _maybeEncode(s):
  511.         if isinstance(s, unicode):
  512.             s = s.encode('utf-8')
  513.         return s
  514.     urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
  515.     if original.scheme:
  516.         # TODO: handle Unicode (see #2409)
  517.         yield "%s://%s" % (original.scheme, original.netloc)
  518.     for pathsegment in original._qpathlist:
  519.         yield '/'
  520.         yield serialize(_maybeEncode(pathsegment), urlContext)
  521.     query = original._querylist
  522.     if query:
  523.         yield '?'
  524.         first = True
  525.         for key, value in query:
  526.             if not first:
  527.                 # xhtml can't handle unescaped '&'
  528.                 if context.isAttrib is True:
  529.                     yield '&'
  530.                 else:
  531.                     yield '&'
  532.             else:
  533.                 first = False
  534.             yield serialize(_maybeEncode(key), urlContext)
  535.             if value is not None:
  536.                 yield '='
  537.                 yield serialize(_maybeEncode(value), urlContext)
  538.     if original.fragment:
  539.         yield "#"
  540.         yield serialize(_maybeEncode(original.fragment), urlContext)
  541.  
  542.  
  543. def URLOverlaySerializer(original, context):
  544.     if context.precompile:
  545.         yield original
  546.     else:
  547.         url = original.urlaccessor(context)
  548.         for (cmd, args, kw) in original.dolater:
  549.             url = getattr(url, cmd)(*args, **kw)
  550.         req = context.locate(inevow.IRequest)
  551.         for key in original._keep:
  552.             for value in req.args.get(key, []):
  553.                 url = url.add(key, value)
  554.         yield serialize(url, context)
  555.  
  556.  
  557. ## This is totally unfinished and doesn't work yet.
  558. #class IURLGenerator(compy.Interface):
  559. #    pass
  560.  
  561.  
  562. class URLGenerator:
  563.     #implements(IURLGenerator)
  564.  
  565.     def __init__(self):
  566.         self._objmap = weakref.WeakKeyDictionary()
  567.  
  568.     def objectMountedAt(self, obj, at):
  569.         self._objmap[obj] = at
  570.  
  571.     def url(self, obj):
  572.         try:
  573.             return self._objmap.get(obj, None)
  574.         except TypeError:
  575.             return None
  576.  
  577.     __call__ = url
  578.  
  579.     def __getstate__(self):
  580.         d = self.__dict__.copy()
  581.         del d['_objmap']
  582.         return d
  583.  
  584.     def __setstate__(self, state):
  585.         self.__dict__ = state
  586.         self._objmap = weakref.WeakKeyDictionary()
  587.  
  588.  
  589. class URLRedirectAdapter:
  590.     """Adapter for URL and URLOverlay instances that results in an HTTP
  591.     redirect.
  592.  
  593.     Whenever a URL or URLOverlay instance is returned from locateChild or
  594.     renderHTTP an HTTP response is generated that causes a redirect to
  595.     the adapted URL. Any remaining segments of the current request are
  596.     consumed.
  597.  
  598.     Note that URLOverlay instances are lazy so their use might not be entirely
  599.     obvious when returned from locateChild, i.e. url.here means the request's
  600.     URL and not the URL of the resource that is self.
  601.  
  602.         def renderHTTP(self, ctx):
  603.             # Redirect to my immediate parent
  604.             return url.here.up()
  605.  
  606.         def locateChild(self, ctx, segments):
  607.             # Redirect to the URL of this resource
  608.             return url.URL.fromContext(ctx)
  609.     """
  610.     implements(inevow.IResource)
  611.  
  612.     def __init__(self, original):
  613.         self.original = original
  614.  
  615.     def locateChild(self, ctx, segments):
  616.         return self, ()
  617.  
  618.     def renderHTTP(self, ctx):
  619.         # The URL may contain deferreds so we need to flatten it using
  620.         # flattenFactory that will collect the bits into the bits list and
  621.         # call flattened to finish.
  622.         bits = []
  623.         def flattened(spam):
  624.             # Join the bits to make a complete URL.
  625.             u = ''.join(bits)
  626.             # It might also be relative so resolve it against the current URL
  627.             # and flatten it again.
  628.             u = flat.flatten(URL.fromContext(ctx).click(u), ctx)
  629.             return redirectTo(u, inevow.IRequest(ctx))
  630.         return flat.flattenFactory(self.original, ctx, bits.append, flattened)
  631.